import { Component } from '@angular/core';
import {
  AlertController, IonicPage, Loading, LoadingController, NavController, NavParams,
  Platform
} from 'ionic-angular';
import { ApiProvider } from "../../providers/api/api";
import { LocalStorProvider } from "../../providers/local-stor/local-stor";
import { SourceViewProvider } from "../../providers/source-view/source-view";
import { ThemeableBrowserObject } from "@ionic-native/themeable-browser";
import { BackButtonProvider } from "../../providers/back-button/back-button";
import { FileTransferObject, FileTransfer } from "@ionic-native/file-transfer";
/*import {ViewSourcePage} from "../view-source/view-source";*/
import { downloadInfo } from "../../modal/downloadInfo";
import { ExerciseAnswerPage } from "../exercise-answer/exercise-answer";
import { CreateBullentPage } from "../create-bullent/create-bullent";
import { now } from '../../../node_modules/moment';

/**
 * Generated class for the UnitExerciseListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-unit-source-list',
  templateUrl: 'unit-source-list.html',
})
export class UnitSourceListPage {
  classType="60002";
  sourceType = "xt";

  scoreTitle = "分值";

  classCourseId;
  teacherId;
  unitId;

  studentId;
  lastTime:"now";
  sourceList;//接收数据

  themeableBrowser: ThemeableBrowserObject;

  inTime;
  backTime;
  source_idStr;

  come_from = 0;
  show = false;

  // 搜索框内容
  searchInput;
  showSearchBar = false;

  downloadInfo: downloadInfo[] = [];

  viewSourceState = true;

  startOrNot:0;//是否开始答题
  classcourseId;


  classcourseIdbd;
  constructor(public navCtrl: NavController, public navParams: NavParams, public http: ApiProvider, public storage: LocalStorProvider, public souceview: SourceViewProvider,
    public platform: Platform, private alertCtrl: AlertController, private transfer: FileTransfer, public loadingCtrl: LoadingController) {
  }

  ionViewDidLoad() {
    /*    this.storage.getKey("downLoadInfo").then(val=>{
          this.downloadInfo=val;
        });

        if(this.come_from==1)
        {
          //alert("查看资源返回了！");
        }
        this.classCourseId=this.navParams.get("classCourseId");
        this.teacherId=this.navParams.get("teacherId");
        this.unitId=this.navParams.get("unitId");
        this.studentId=this.navParams.get("studentId");

        this.classType=this.navParams.get("classType");
        this.sourceType=this.navParams.get("sourceType");
        this.sourceType=this.navParams.get("sourceType");
        this.getSourceList();*/
  }

  ionViewWillEnter() {
    /*    alert("1:"+localStorage.getItem("class_type"));
        this.classType=localStorage.getItem("class_type");
        alert("2:"+this.classType);*/
  }

  ionViewDidEnter() {
    // this.classType = localStorage.getItem("class_type");

    this.storage.getKey("downLoadInfo").then(val => {
      this.downloadInfo = val;
    });

    if (this.come_from == 1) {
      //alert("查看资源返回了！");
    }
    this.classCourseId = this.navParams.get("classCourseId");
    // this.classcourseId = this.navParams.get("classCourseId");
    this.teacherId = this.navParams.get("teacherId");
    this.unitId = this.navParams.get("unitId");
    console.log("classType: "+this.classType+"sourceType: "+this.sourceType+"classCourseId: "+this.classCourseId+"teacherId: "+this.teacherId+"unitId: "
    +this.unitId+"studentId: "+this.studentId)
    this.studentId = this.navParams.get("studentId");

    // this.classType = this.navParams.get("classType");

    this.sourceType = this.navParams.get("sourceType");



    this.getSourceList();
  }

  ionViewDidLeave() {
    //this.storage.remove("class_type");
  }

  /**
   * 切换习题或资源时重置课堂环节
   */
  IninClassType(type) {
    this.sourceType = type;
    this.classType = "60002";
    localStorage.setItem("class_type", this.classType);

    if (this.sourceType == "xt") {
      this.show = false
      this.scoreTitle = "分值";
    } else {
      this.show = true
      this.scoreTitle = "经验值";
    }

    this.getSourceList();
  }

  /**
   * 切换课前课中课后
   * @param classType
   */
  changeClassType(classType) {
    localStorage.setItem("class_type", classType);
    this.classType = classType;

    this.getSourceList();
  }

  /**
   * 获取相应类型的资源列表数据
   */
  getSourceList() {
    this.classType = localStorage.getItem("class_type");

    let loading = this.loadingCtrl.create({
      content: '正在加载',
      showBackdrop: false,
      dismissOnPageChange: true
    });
    loading.present();
    //console.log(this.classType)
    if(this.show){
      //资源
      this.http.post("/unitTeacherController/teachSourceListByTypeOfTeacher.do", {
        // classCourseId: this.classCourseId, teacherId: +this.teacherId, classType: this.classType,
        // unitId: this.unitId, sourceType: this.sourceType, action: "up", requestTime: "now", studentId: this.studentId,
        userId:this.teacherId,unitId:this.unitId,classtype:this.classType,requestTime:this.lastTime
      }).subscribe(item => {
        console.log(item)
        if (item["Code"] == "11111111") {
          loading.dismiss();
          this.http.showToast(item["Message"], "bottom");
        }
        else {
          this.sourceList = item["data"];

          console.log(this.sourceList);
          loading.dismiss();



          //console.log(item["sourceList"]);
          //this.sourceList = item["sourceList"];

          //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
          // for (let source of this.sourceList) {
          //   //讲义、PDF、视频获取下载状态
          //   if (source["source_type"] == "40005" || source["source_type"] == "40011" || source["source_type"] == "40009") {
          //     source["isCheck"] = this.getDownloadState(source["sourceid"]);
          //   }
          // }
          //loading.dismiss();
        }
      });
    }else{
      //习题
      this.classcourseIdbd = localStorage.getItem("classcourseIdb");
      this.http.post("/unitTeacherController/getExeByUnitOfTeacher.do", {
        // classCourseId: this.classCourseId, teacherId: +this.teacherId, classType: this.classType,
        // unitId: this.unitId, sourceType: this.sourceType, action: "up", requestTime: "now", studentId: this.studentId,
        Classcourseid: this.classCourseId,userId:this.teacherId,unitId:this.unitId,requestTime:this.lastTime
      }).subscribe(item => {
        console.log(item)
        if (item["Code"] == "11111111") {
          loading.dismiss();
          this.http.showToast(item["Message"], "bottom");
        }
        else {
          this.sourceList = item["data"];
          //console.log(this.sourceList);
          loading.dismiss();



          //console.log(item["sourceList"]);
          //this.sourceList = item["sourceList"];

          //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
          // for (let source of this.sourceList) {
          //   //讲义、PDF、视频获取下载状态
          //   if (source["source_type"] == "40005" || source["source_type"] == "40011" || source["source_type"] == "40009") {
          //     source["isCheck"] = this.getDownloadState(source["sourceid"]);
          //   }
          // }
          //loading.dismiss();
        }
      });
    }

  }

  /**
   * 下拉刷新
   * @param refresher
   */
   doRefresh(refresher) {
    let loading = this.loadingCtrl.create({

    });
    let curAction = '';
    if (this.sourceList.length > 0) {
      curAction = 'down';                                                         //?
    }
    else {
      curAction = 'up';
    }
    // let loading = this.loadingCtrl.create({
    //   content: '正在加载',
    //   showBackdrop: false,
    //   dismissOnPageChange: true
    // });
    // loading.present();

    //let lastTime;

    if (this.sourceList.length == 0)
      this.lastTime = "now";
    else
      this.lastTime = this.sourceList[this.sourceList.length - 1].create_time;                                //?
      //console.log(this.lastTime)
      setTimeout(() => {
        refresher.complete();
        loading.dismiss();
      }, 2000);

    this.getSourceList();

    // this.http.post("/source/getSourceList.do", {
    //   classCourseId: this.classCourseId, teacherId: +this.teacherId, classType: this.classType,
    //   unitId: this.unitId, sourceType: this.sourceType, action: curAction, requestTime: lastTime, studentId: this.studentId
    // }).subscribe(item => {
    //   if (item["Code"] == "11111111") {
    //     loading.dismiss();
    //     this.http.showToast(item["Message"], "bottom");
    //   }
    //   else {
    //     setTimeout(() => {
    //       this.sourceList = item["sourceList"];

    //       //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
    //       for (let source of this.sourceList) {
    //         //讲义、PDF、视频获取下载状态
    //         if (source["source_type"] == "40005" || source["source_type"] == "40011" || source["source_type"] == "40009") {
    //           source["isCheck"] = this.getDownloadState(source["sourceid"]);
    //         }
    //       }

    //       refresher.complete();
    //       loading.dismiss();
    //     }, 2000);
    //   }
    // });
  }

  /**
   * 资源查看
   * @param path 路径
   * @param title 标题
   * @param sourceId 资源id
   * @param sourceType 资源类型
   * @param source_id 资源id-教师id-资源类型拼接串
   * @param isCheck 是否下载，查看，或答题
   * @param num 习题索引
   * @param start_answer 是否开始答题，答题状态
   * @param start_time 课中习题开始答题时间
   * @constructor
   */
  ViewSource(path, title, sourceId, sourceType, source_id, isCheck, num, start_answer, start_time, answer_type) {
    localStorage.setItem("class_type", this.classType);
    if (!this.viewSourceState)
      return;

    this.viewSourceState = false;


    setTimeout(() => { this.viewSourceState = true }, 1000);

    this.come_from = 1;
    //计时
    this.inTime = Date.parse(new Date().toString());

    this.source_idStr = source_id;
    if (this.sourceType == 'zy') {
      let url = '';
      if (sourceType == "40003")//网页链接
      {
        url = path;
      }
      else if (sourceType == "40002" || sourceType == "40010" || sourceType == "40009")//案例、图片、视频
      {
        url = this.http.filePath + path;
      }
      else if (sourceType == "40005" || sourceType == "40011")//讲义和pdf
      {
        if (isCheck == 0 || isCheck == 3 || isCheck == 4) {
          this.http.showToast("该类型资源不能在线预览，请下载后打开", "bottom");
          return;
        }
        else {
          url = path;
        }
      }

      //之前没有查看过，则先调取查看接口，之后不再次调取
      //2018-07-02 新增需求 资源已开始可以记录查看资源记录，若资源已停止则不记录
      if (isCheck == 0 && (sourceType != "40005" && sourceType != "40011") && start_answer == 1) {
        this.http.post("/source/checkSource.do", {
          teacherId: +this.teacherId, studentId: this.studentId, inUnitId: this.unitId,
          classCourseId: this.classCourseId, sourceId: sourceId, sourceSign: 1, sourceType: sourceType, classType: this.classType
        }).subscribe(item => {
          if (item["Code"] == "11111111") {
            this.http.showToast(item["Message"], "bottom");
          }
          /*          else
                    {
                      //计时
                      // this.inTime=Date.parse(new Date().toString());
                    }*/
        })
      }

      //新开页面打开各种资源
      //this.navCtrl.push(ViewSourcePage,{path:url,title:title,type:sourceType,studentId:this.studentId,source_idStr:source_id});

      //视频用原生方式打开
      if (sourceType == "40009") {
        this.souceview.showVideo(url);
      }
      //案例，图片，网页链接用主题浏览器打开
      else if (sourceType == "40002" || sourceType == "40010" || sourceType == "40003") {
        //console.log(url);
        this.themeableBrowser = this.souceview.showPage(url, title);

        //后退更新查看时长
        this.themeableBrowser.on("backPressed").subscribe(item => {
          this.backTime = Date.parse(new Date().toString());
          let look_time = (this.backTime - this.inTime) / 1000;

          //2018-07-02 新增需求 资源已开始可以记录查看资源时长，若资源已停止则不记录查看时长
          if (start_answer == 1) {
            this.updataLookTime(look_time);
          }

          this.viewSourceState = true;
        });

        //关闭更新查看时长
        this.themeableBrowser.on("closePressed").subscribe(item => {
          this.backTime = Date.parse(new Date().toString());
          let look_time = (this.backTime - this.inTime) / 1000;

          //2018-07-02 新增需求 资源已开始可以记录查看资源时长，若资源已停止则不记录查看时长
          if (start_answer == 1) {
            this.updataLookTime(look_time);
          }

          this.viewSourceState = true;
        });
      }
      else if ((sourceType == "40005" || sourceType == "40011") && isCheck == 1) {
        this.souceview.openFile(url);
      }
    }
    else {
      //习题
      //进入习题作答页面
      this.navCtrl.push(ExerciseAnswerPage, {
        exerciseType: sourceType, exerciseNo: (+num) + 1, teacherId: this.teacherId, studentId: this.studentId, exerciseId: sourceId,
        unitId: this.unitId, classCourseId: this.classCourseId, classType: this.classType, start_answer: start_answer, start_time: start_time, answer_type: answer_type
      });

    }
  }

  /**
   * 回写资源查看时长
   */
  updataLookTime(lookTime) {
    this.http.post("/exercise/updateLooktime.do", { studentId: this.studentId, sourceId: this.source_idStr, looktime: lookTime }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
    });
  }

  /**
   * 下载文档（讲义，pdf,视频）
   * 首次？？下载文件时调用checksource接口
   * @param path
   * @param e
   * @constructor
   */
  downLoadFile(isCheck, path, e, sourceId, sourceType, index, start_answer) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    //阻止事件冒泡
    e.stopPropagation();

    //之前已下载过，询问是否重新下载？
    if (isCheck == 1) {
      let confirm = this.alertCtrl.create({
        title: '温馨提示',
        message: '当前资源已存在，是否重新下载？',
        buttons: [
          {
            text: '取消',
            handler: () => {
            }
          },
          {
            text: '是',
            handler: () => {
              this.sourceList[index]["isCheck"] = 2;
              let url = this.http.filePath + path;
              fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) => {
                this.sourceList[index]["isCheck"] = 1;
                this.addDownLoadInfo(sourceId, 1);
              }).catch((error) => {
                this.sourceList[index]["isCheck"] = 3;
                this.addDownLoadInfo(sourceId, 4);
              });
            }
          }
        ]
      });
      confirm.present();
    }
    else if (isCheck == 3 || isCheck == 4) {
      let confirm = this.alertCtrl.create({
        title: '温馨提示',
        message: '下载文件失败，是否重新下载？',
        buttons: [
          {
            text: '取消',
            handler: () => {
            }
          },
          {
            text: '是',
            handler: () => {
              this.sourceList[index]["isCheck"] = 2;
              let url = this.http.filePath + path;

              fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) => {
                this.sourceList[index]["isCheck"] = 1;
                this.addDownLoadInfo(sourceId, 1);
              }).catch((error) => {
                this.sourceList[index]["isCheck"] = 3;
                this.addDownLoadInfo(sourceId, 4);
                /*                setTimeout(()=>{
                                  this.sourceList[index]["isCheck"]=3;
                                  this.addDownLoadInfo(sourceId,4);
                                },200);*/
              });
            }
          }
        ]
      });
      confirm.present();
    }
    else {
      this.sourceList[index]["isCheck"] = 2;

      let url = this.http.filePath + path;
      fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) => {
        this.sourceList[index]["isCheck"] = 1;
        this.addDownLoadInfo(sourceId, 1);
      }).catch((error) => {
        this.sourceList[index]["isCheck"] = 3;
        this.addDownLoadInfo(sourceId, 4);
      });

      //2018-07-02 新增需求 资源已开始可以记录查看资源记录，若资源已停止则不记录
      if (start_answer == 1) {
        this.http.post("/source/checkSource.do", {
          teacherId: +this.teacherId, studentId: this.studentId, inUnitId: this.unitId,
          classCourseId: this.classCourseId, sourceId: sourceId, sourceSign: 1, sourceType: sourceType, classType: this.classType
        }).subscribe(item => {
          if (item["Code"] == "11111111") {
            this.http.showToast(item["Message"], "bottom");
          }
        })
      }
    }
  }

  /**
   * 添加下载记录（目前是按最后一次下载状态为准，每次替换之前的）
   * @param sourceId
   * @param state
   */
  addDownLoadInfo(sourceId, state) {
    let flag = 0;
    for (let item of this.downloadInfo) {
      if (item.studentId == this.studentId && item.sourceId == sourceId) {
        flag = 1;
        item.state = state;
      }
    }

    if (flag == 0) {
      this.downloadInfo.push({ sourceId: sourceId, state: state, studentId: this.studentId });
    }

    this.storage.setKey("downLoadInfo", this.downloadInfo);
  }

  /**
   * 从缓存中获取下载相应学生相应资源的下载状态
   * @param sourceid
   * @returns {number}
   */
  getDownloadState(sourceid) {
    let flag = 0;
    for (let item of this.downloadInfo) {
      if (item.studentId == this.studentId && item.sourceId == sourceid) {
        flag = item.state;
        break;
      }
    }
    return flag;
  }

  // 查询接口
  search() {
    this.showSearchBar = !this.showSearchBar
  }
  //推送资源
  pushResources(sourceid:string,sourcetype:string ,unitid:string ){
    console.log("sourceid"+sourceid,"sourcetype"+sourcetype,"unitid"+unitid)

    this.http.post("/unitTeacherController/publishSpecificSouceOfTeacher.do", {
      userId:this.teacherId , unit_id:this.unitId , course_class_id:this.classCourseId , source_id:sourceid , source_type:sourcetype
    }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }else{
        console.log(item)
        let alert = this.alertCtrl.create({
          title: '发送成功',
      buttons: [
        {
          text: '确定',
          role: 'cancel',
          handler: () => {

          }
        }]
        })
        alert.present();
      }
    })
  }

  //开始答题
  sTheAnswer(teacher_id:string,unit_id:string,course_class_id:string,source_id:string,source_type:string,start_answer:number){
    //console.log(teacher_id,unit_id,course_class_id,source_id,source_type)

    if(start_answer==1){
      start_answer=0
    }else{
      start_answer=1
    }

    console.log(start_answer)
    this.http.post("/unitTeacherController/updatePublishTeacher.do", {
      userId:teacher_id , unitId:unit_id , classCourseId:course_class_id , sourceId:source_id , sourceType:source_type , classType:60002 , startAnswer:start_answer
    }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }else{
        console.log(item)
        this.getSourceList();
      }
    })

  }

}
